package cn.lls.config;

import cn.lls.interceptor.CAInterceptor;
import cn.lls.interceptor.CommonInterceptor;
import cn.lls.interceptor.SAInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 拦截器配置类
 * @ClassName SAConfig
 * @Author 划水艺术家
 * @Date 2022/11/16 15:48
 * @Version 1.0
 **/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private SAInterceptor saInterceptor;

    @Autowired
    private CAInterceptor caInterceptor;

    @Autowired
    private CommonInterceptor commonInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器，通过拦截器来拦截特定路径的请求来对用户进行 token 鉴权
        /*
        * 对 超级管理员 的相关接口做拦截，除登录
        * */
        registry.addInterceptor(saInterceptor)
                .addPathPatterns("/sa/**").excludePathPatterns("/sa/login")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        /*
         * 对 单位管理员的的相关接口做拦截，除登录
         * */
        registry.addInterceptor(caInterceptor)
                .addPathPatterns("/ca/**").excludePathPatterns("/ca/login", "/ca/enroll")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
//        /*
//         * 对 通用操作的相关接口做拦截，除登录
//         * */
//        registry.addInterceptor(commonInterceptor)
//                .addPathPatterns("/common/**")
//                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }

    /***
     * 配置静态资源访问拦截
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 添加映射路径
        registry.addMapping("/**")
                .allowedHeaders("*")  // 允许跨域请求包含任意的头信息
                .allowedMethods("*")  // 设置允许的方法
                .allowedOrigins("*")  // 设置允许跨域请求的域名
                .allowCredentials(true);  // 是否允许证书，默认false
    }
}
